package com.uidt.project.ptsj.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.uidt.common.utils.DictUtils;
import com.uidt.common.utils.StringUtils;
import com.uidt.framework.redis.RedisCache;
import com.uidt.framework.web.domain.AjaxResult;
import com.uidt.project.ptsj.domain.*;
import com.uidt.project.ptsj.mapper.PtsjScreenPlaceRoomNumMapper;
import com.uidt.project.ptsj.mapper.ScreenCountMapper;
import com.uidt.project.ptsj.obj.ScreenSeachObj;
import com.uidt.project.ptsj.service.IScreenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ScreenServiceImpl implements IScreenService {
    @Autowired
    ScreenCountMapper screenCountMapper;

    @Autowired
    PtsjScreenPlaceRoomNumMapper ptsjScreenPlaceRoomNumMapper;

    @Autowired
    private DataSyncServiceImpl dataSyncServiceImpl;
    @Autowired
    RedisCache redisCache;

    private static List<String> eventSourceTypes = new ArrayList<>();

    private static List<String> areaList= new ArrayList<>();

    private static Map<String,String> qxMap = new HashMap<>();

    private static LinkedHashMap<String,String> dwCodeMap = new LinkedHashMap<>();
    static {
        eventSourceTypes.add("旅客投诉");
        eventSourceTypes.add("房东申诉");
        eventSourceTypes.add("内部流转");
        eventSourceTypes.add("综治办推送");

//        areaList.add("330999080000,朱家尖");// 朱家尖
        areaList.add("330999620000,普陀山");//普陀

        qxMap.put("330902","定海");
        qxMap.put("330903","普陀");
        qxMap.put("330921","岱山");
        qxMap.put("330922","嵊泗");
        qxMap.put("330998","新城");
        qxMap.put("330999","普朱");

        dwCodeMap.put("GA","公安");
        dwCodeMap.put("XZ","行政");
        dwCodeMap.put("WS","卫生");
        dwCodeMap.put("SJ","市监");
        dwCodeMap.put("XF","消防");
        dwCodeMap.put("XH","协会");
        dwCodeMap.put("ZJ","住建");


    }

    @Override
    public List<CountItem> getScoreRank(ScreenSeachObj screenSeachObj){
        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));
        List<CountItem> list = new ArrayList<>();
        CountItem max = screenCountMapper.selectScoreMax(changeGxdwdm(gxdwdmList));
        max.setTitle("得分最高");
        CountItem min = screenCountMapper.selectScoreMin(changeGxdwdm(gxdwdmList));
        min.setTitle("得分最低");
        list.add(max);
        list.add(min);
        return list;
    }

    @Override
    public List<CountItem> getScoreList(ScreenSeachObj screenSeachObj){
        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));
        return screenCountMapper.getScoreList(changeGxdwdm(gxdwdmList));
    }

    @Override
    public List<CountItem> getColorCount(ScreenSeachObj screenSeachObj) {
        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));
        HashMap<String, BigDecimal> colorCount = screenCountMapper.getColorCount(changeGxdwdm(gxdwdmList));
        List<CountItem> list = new ArrayList<>();
        CountItem countItem = new CountItem();
        countItem.setName("停业整顿");
        if(colorCount.get("red") == null) {
            countItem.setCount(0);
        }else {
            countItem.setCount(colorCount.get("red").intValue());
        }
        list.add(countItem);
        countItem = new CountItem();
        countItem.setName("提醒整改");
        if(colorCount.get("yellow") == null) {
            countItem.setCount(0);
        }else {
            countItem.setCount(colorCount.get("yellow").intValue());
        }
        list.add(countItem);
        countItem = new CountItem();
        countItem.setName("行业警告");
        if(colorCount.get("blue") == null) {
            countItem.setCount(0);
        }else {
            countItem.setCount(colorCount.get("blue").intValue());
        }
        list.add(countItem);
        return list;
    }

    @Override
    public List<CountItem> getStatusCount() {
        List<CountItem> statusCountList = screenCountMapper.getStatusCount();
        int total = 0;
        HashMap<String, CountItem> statusMap = new HashMap<>(statusCountList.size());
       for (CountItem countItem : statusCountList) {
            statusMap.put(countItem.getName().trim(), countItem);
           total = total + countItem.getCount();
        }
        System.out.println(statusMap);
        statusCountList = new ArrayList<>();
        for (int i=1;i<4;i++) {
            CountItem countItem = new CountItem();
            if (statusMap.containsKey(i)) {
                countItem = statusMap.get(i);
            }
            countItem.setName(DictUtils.getDictLabel("ptsj_status_list", String.valueOf(i)));
            countItem.setPercent(String.format("%.2f", countItem.getCount() * 100 / total));
            statusCountList.add(countItem);
        }
        return statusCountList;
    }

    @Override
    public List<Map<String,String>> getStarsCount(ScreenSeachObj screenSeachObj) {

        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));

        List<Map<String,String>> list = screenCountMapper.getStarsCount(changeGxdwdm(gxdwdmList));
        // 初始化resultList
        List<Map<String,String>> resultList = new ArrayList<>();
        // 初始化map
        Map<String,Map<String,String>> map = new HashMap<>();
        for(String areaCode:areaList){
            Map<String,String> itemMap = new HashMap<>();
            itemMap.put("name",areaCode.split(",")[1]);
            itemMap.put("sx","0");
            itemMap.put("ex","0");
            itemMap.put("yx","0");
            map.put(areaCode.split(",")[0],itemMap);
        }
        for(Map tempmap:list){
            String key = tempmap.get("gxdwdm").toString();
            Map<String,String> itemMap = map.get(key);
            if("1".equals(tempmap.get("name").toString())){
                // 一星
                itemMap.put("yx",tempmap.get("count").toString());
            }else if("2".equals(tempmap.get("name").toString())){
                // 二星
                itemMap.put("ex",tempmap.get("count").toString());
            }else if("3".equals(tempmap.get("name").toString())){
                // 三星
                itemMap.put("sx",tempmap.get("count").toString());
            }
        }
        for(String key :map.keySet()){
            resultList.add(map.get(key));
        }


        return resultList;
    }

    @Override
    public List<CountItem> listGuestCount() {
        List<CountItem>  list = dataSyncServiceImpl.getGuestCountList();
        Collections.sort(list, new Comparator<CountItem>() {
            @Override
            public int compare(CountItem p1, CountItem p2) {
                return p2.getCount() - p1.getCount();
            }
        });
        System.out.println(JSONObject.toJSONString(list));
        double total = 0;
        for(CountItem countItem : list) {
            total = total + countItem.getCount();
        }
        List<CountItem> result = new ArrayList<>();
        int otherCount = 0;
        for(int i=0;i<list.size();i++) {
            CountItem countItem = list.get(i);
            if(i<5) {
                countItem.setPercent(String.format("%.2f", countItem.getCount() * 100 / total));
                result.add(countItem);
            }else {
                otherCount = otherCount + countItem.getCount();
            }
        }
        CountItem countItem = new CountItem();
        countItem.setName("其他");
        countItem.setCount(otherCount);
        countItem.setPercent(String.format("%.2f", otherCount * 100 / total));
        result.add(countItem);
        return result;
    }

    @Override
    public List<Warning> getWarning() {
        return screenCountMapper.getWarningList();
    }

    @Override
    public AjaxResult qsBigscreenCenterData() {

        Map<String,Map<String,String>> map = new HashMap<>();

        /*根据区县分组，计算场所数量*/
        List<Map<String,String>> placeList =  screenCountMapper.getPlaceCountGroupByGxdm();

        /*根据区县分组，计算房源数量*/
        List<Map<String,String>> houseList = screenCountMapper.getHouseCountGroupByGxdm();
//
//        /*根据区县分组，计算经营主体数量*/
//        List<Map<String,String>> ownerList = screenCountMapper.getOwnerCountGroupByGxdm();
//
//        /*根据区县分组，计算当日入住数量*/
//        List<Map<String,String>> rzList  = screenCountMapper.getRzCountGroupByGxdm();


        for(String key:qxMap.keySet()){
            Map<String,String> subMap = new HashMap<>();
            subMap.put("cssl","0");
            subMap.put("fysl","0");

            for(Map placeMap:placeList){
                if(key.equals(placeMap.get("gxdwdm"))){
                    subMap.put("cssl",placeMap.get("num").toString());
                }
            }
            for(Map houseMap:houseList){
                if(key.equals(houseMap.get("gxdwdm"))){
                    subMap.put("fysl",houseMap.get("num").toString());
                }
            }
            map.put(qxMap.get(key),subMap);
        }



        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult qxBigscreenCenterData(ScreenSeachObj screenSeachObj) {

        String gxdwdm = screenSeachObj.getGxdwdm();

        // 朱普取PtsjScreenPlaceRoomNum表的数据
        if(gxdwdm.equals("330999080000")|| gxdwdm.equals("330999620000")){
            PtsjScreenPlaceRoomNum ptsjScreenPlaceRoomNum = new PtsjScreenPlaceRoomNum();
            ptsjScreenPlaceRoomNum.setGxdwdm(screenSeachObj.getGxdwdm());
            List<PtsjScreenPlaceRoomNum> list = ptsjScreenPlaceRoomNumMapper.selectPtsjScreenPlaceRoomNumList(ptsjScreenPlaceRoomNum);
            return AjaxResult.success(list);
        }else {
            // 其他区县，从place和room表中统计,根据派出所管辖单位代码全码统计
//            List<Map<String,String>> placeCountList = screenCountMapper.getPlaceCountGroupByGxdm();
            List<Map<String,String>> placeCountList = screenCountMapper.getPlaceCountGroupByGxdmAll(gxdwdm.substring(0,6));
            List<Map<String,String>> houseCountList = screenCountMapper.getHouseCountGroupByGxdmAll(gxdwdm.substring(0,6));
            Map<String,PtsjScreenPlaceRoomNum> map = new HashMap<>();
            for(Map<String,String> temp:placeCountList){
                PtsjScreenPlaceRoomNum placeRoomNum;
                if(map.containsKey(temp.get("gxdwdm"))){
                    placeRoomNum = map.get(temp.get("gxdwdm"));
                }else {
                    placeRoomNum = new PtsjScreenPlaceRoomNum();
                }
                placeRoomNum.setName(temp.get("gxdwmc"));
                placeRoomNum.setPlacecount(String.valueOf(temp.get("num")));
                map.put(temp.get("gxdwdm"),placeRoomNum);
            }
            for(Map<String,String> temp:houseCountList){
                PtsjScreenPlaceRoomNum placeRoomNum;
                if(map.containsKey(temp.get("gxdwdm"))){
                    placeRoomNum = map.get(temp.get("gxdwdm"));
                }else {
                    placeRoomNum = new PtsjScreenPlaceRoomNum();
                }
                placeRoomNum.setName(temp.get("gxdwmc"));
                placeRoomNum.setRoomcount(String.valueOf(temp.get("num")));
                map.put(temp.get("gxdwdm"),placeRoomNum);
            }

            List<PtsjScreenPlaceRoomNum> list = new ArrayList<>();
            for(String key : map.keySet()){
                list.add(map.get(key));
            }

            return AjaxResult.success(list);
        }



    }


    /*
    * 事件来源统计
    * */
    @Override
    public List<CountItem> getEventSourceCount(ScreenSeachObj screenSeachObj) {
        EventCountVo eventCountVo = new EventCountVo();

        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));

        List<CountItem> sourceList = screenCountMapper.getEventSourceCount(gxdwdmList);
        List<CountItem> sourceList2 = new ArrayList<>();
        List<String> temp = new ArrayList<>();
        double total = 0;
        for (CountItem item : sourceList) {
            // 当事件来源属于4种之一的话，才计算总数
            if(eventSourceTypes.contains(item.getName())){
                total = total + item.getCount();
                sourceList2.add(item);
                temp.add(item.getName());
            }
        }

        for(String eventSourceType:eventSourceTypes){
           if(!temp.contains(eventSourceType)){
               CountItem countItem = new CountItem();
               countItem.setCount(0);
               countItem.setName(eventSourceType);
               sourceList2.add(countItem);
           }
        }

        System.out.println(total);
        for (CountItem item : sourceList2) {
            if(item.getName().equals("综治办推送")){
                item.setName("12345推送");
            }
            item.setPercent(String.format("%.2f", item.getCount() * 100 / total));
        }
        eventCountVo.setScourceCountList(sourceList2);
        return sourceList2;
    }

    @Override
    public List<CountItem> getEventDepartmentCount(ScreenSeachObj screenSeachObj) {
        List<String> gxdwdmList = new ArrayList<>();
        if(StringUtils.isNotEmpty(screenSeachObj.getGxdwdm())){
            gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));
        }


        List<Map<String,String>> doneMap = screenCountMapper.getEventDepartmentDoneCount(gxdwdmList);
        List<Map<String,String>> undoneMap = screenCountMapper.getEventDepartmentUnDoneCount(gxdwdmList);
//        String deptlist = DictUtils.getDictLabels("ptsj_dept_list");
//        String departments[] = deptlist.split(",");

        LinkedHashMap<String,CountItem> resultMap = new LinkedHashMap<>();
        List<CountItem> resultList = new ArrayList<>();
        //初始化数据
        for(String key:dwCodeMap.keySet()){
            CountItem countItem = new CountItem();
            countItem.setName(dwCodeMap.get(key));

            int done = 0;
            int unDone = 0;
            for(Map map:doneMap){
                if(map.get("proc_dept_code")!=null && map.get("proc_dept_code").toString().endsWith(key)){
                    done+=Integer.parseInt(map.get("num").toString());
                }
            }
            for(Map map:undoneMap){
                if(map.get("proc_dept_code")!=null && map.get("proc_dept_code").toString().endsWith(key)){
                    unDone+=Integer.parseInt(map.get("num").toString());
                }
            }
            countItem.setDone(done);
            countItem.setUnDone(unDone);
            resultMap.put(dwCodeMap.get(key),countItem);
        }
        for(String key:resultMap.keySet()){
            resultList.add(resultMap.get(key));
        }
        return resultList;
    }

    @Override
    public List<EventInfo> listEvent(ScreenSeachObj screenSeachObj){

        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));
        List<EventInfo> list = screenCountMapper.listEvent(gxdwdmList,screenSeachObj.getType());
        return list ;
    }

    @Override
    public  List<Inspection> listLastInspection(ScreenSeachObj screenSeachObj){

        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));
        List<Inspection> list = screenCountMapper.listLastInspection(gxdwdmList);

        return list;
    }

    @Override
    public List<CountItem> getRoomCount(ScreenSeachObj screenSeachObj) {
        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));

        List<CountItem> list = new ArrayList<>();

        CountItem placeCount = screenCountMapper.getPlaceCount(changeGxdwdm(gxdwdmList));
        placeCount.setName("场所总数");
        list.add(placeCount);

        CountItem roomCount = screenCountMapper.getRoomCount(changeGxdwdm(gxdwdmList));
        roomCount.setName("房源总数");
        list.add(roomCount);

        double total = roomCount.getCount();
        CountItem countItem = new CountItem();
        countItem.setName("今日入住率");
        String percent = dataSyncServiceImpl.getCheckInTotal2(screenSeachObj.getGxdwdm());

        countItem.setPercent(percent);
        list.add(countItem);
        return list ;

    }

    /*
     * 统计一个月内的巡检数和自查数
     * */
    @Override
    public List<CountItem> getInspectionCount(ScreenSeachObj screenSeachObj){
//        String inspectionType = DictUtils.getDictLabels("ptsj_inspection_type");
        List<CountItem> list = new ArrayList<>();
        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));
        // 巡检记录统计
        Integer count = screenCountMapper.getInspectionCount(gxdwdmList);
        CountItem countItem = new CountItem();
        countItem.setName("日常巡检");
        countItem.setCount(count);
        list.add(countItem);

        Integer count2 = screenCountMapper.getXfzcCount(changeGxdwdm(gxdwdmList));
        countItem = new CountItem();
        countItem.setName("企业自检");
        countItem.setCount(count2);
        list.add(countItem);
        return list;
    }

    @Override
    public List<CountItem> getInspectionDepartmentCount(ScreenSeachObj screenSeachObj) {
        List<String> gxdwdmList = Arrays.asList(screenSeachObj.getGxdwdm().split(","));
        List<CountItem> inspectionCountList = screenCountMapper.getInspectionDepartmentCount(gxdwdmList);

        List<CountItem> returnInspectionCountList = new ArrayList<>();

//        String deptCodelist = DictUtils.getDictLabels("ptsj_dept_code_list");
//        String deptCodeArr[] = deptCodelist.split(",");

        // 循环，并且补0，协会不会来添加巡检记录
        for(String deptCode:dwCodeMap.keySet()){
            if(deptCode.equals("XH")){
                continue;
            }
            boolean flg = true;
            for(CountItem countItem:inspectionCountList){
                if(countItem.getDeptCode().endsWith(deptCode)){
                    countItem.setName(dwCodeMap.get(deptCode));
                    returnInspectionCountList.add(countItem);
                    flg=false;
                    break;
                }
            }
            if(flg){
                CountItem countItem = new CountItem();
                countItem.setName(dwCodeMap.get(deptCode));
                countItem.setCount(0);
                returnInspectionCountList.add(countItem);
            }
        }

//        int total = 0;
//        HashMap<String, CountItem> deptMap = new HashMap<>(departments.length);
//        inspectionCountList.forEach(countItem -> {
//            System.out.println(countItem.toString());
//            deptMap.put(countItem.getName().trim(), countItem);
//        });
//        System.out.println(deptMap);
//        inspectionCountList = new ArrayList<>();
//        for (String dept : departments) {
//            if(dept.equalsIgnoreCase("协会")){
//                continue;
//            }
//            CountItem countItem = new CountItem();
//            if (deptMap.containsKey(dept)) {
//                countItem = deptMap.get(dept);
//                if(countItem.getCount() > 0){
//                    countItem.setPercent(String.format("%.2f", countItem.getDone() * 100 / countItem.getCount()));
//                }
//            } else {
//                countItem.setName(dept);
//                countItem.setPercent("0");
//
//            }
//            inspectionCountList.add(countItem);
//        }
        return returnInspectionCountList;
    }

    private List<String> changeGxdwdm(List<String> list){
        List<String> newList = new ArrayList<>();
        for(String gxdwdm:list){
            if(gxdwdm.equals("330999080000") || gxdwdm.equals("330999620000")){
                newList.add(gxdwdm.substring(0,8));
            }else {
                newList.add(gxdwdm.substring(0,6));
            }
        }
        return newList;
    }

}
